package com.rightsidetech.trade.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.trade.dtos.request.TdCouponUsePageReq;
import com.rightsidetech.trade.dtos.response.TdCouponUsePageResp;
import com.rightsidetech.trade.entity.TdCouponUseRecord;
import com.rightsidetech.trade.mapper.TdCouponUseRecordMapper;
import com.rightsidetech.trade.service.TdCouponUseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-12-29 10:01
 */
@Service("tdCouponUseService")
public class TdCouponUseServiceImpl implements TdCouponUseService {
    @Resource
    private TdCouponUseRecordMapper tdCouponUseRecordMapper;
    @Override
    public ResponseData<PageInfo<TdCouponUsePageResp>> couponUsePage(TdCouponUsePageReq req) {
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<TdCouponUsePageResp> result = tdCouponUseRecordMapper.couponUsePage(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public int insert(TdCouponUseRecord req) {
        return tdCouponUseRecordMapper.insertSelective(req);
    }

    @Override
    public TdCouponUseRecord selectCoupon(String code) {
        return tdCouponUseRecordMapper.selectByCode(code);
    }

    @Override
    public void updateStatusByorderNo(String orderNo, Byte status) {
        TdCouponUseRecord tdCouponUseRecord = tdCouponUseRecordMapper.selectByOrderNo(orderNo);
        if(!StringUtil.isNullorEmpty(tdCouponUseRecord)){
            TdCouponUseRecord tdCouponUseRecord2 = new TdCouponUseRecord();
            tdCouponUseRecord2.setId(tdCouponUseRecord.getId());
            tdCouponUseRecord2.setStatus(status);
            tdCouponUseRecord2.setUpdatedAt(new Date());
            if(status == 1){
                tdCouponUseRecord2.setPayTime(new Date());
            }
            tdCouponUseRecordMapper.updateByPrimaryKeySelective(tdCouponUseRecord2);
        }
    }

    @Override
    public void updateByIdAndCode(Long id, String code) {
        TdCouponUseRecord tdCouponUseRecord = new TdCouponUseRecord();
        tdCouponUseRecord.setId(id);
        tdCouponUseRecord.setUpdatedAt(new Date());
        tdCouponUseRecord.setStatus((byte) 1);
        tdCouponUseRecord.setPayTime(new Date());
        tdCouponUseRecordMapper.updateByPrimaryKeySelective(tdCouponUseRecord);
        //修改使用该优惠券没有付款的订单记录
        tdCouponUseRecordMapper.updateStatusByCodeAndId(code,id);
    }

    @Override
    public TdCouponUseRecord selectByOrderNo(String orderNo) {
        return tdCouponUseRecordMapper.selectByOrderNo(orderNo);
    }

    @Override
    public int delUseCode(String code) {
        return tdCouponUseRecordMapper.delByCode(code);
    }
}
